$().ready(function() {
	list_module();
	get_hash();
	$(".btn-share").click(function(){
		html="";
		html+='<div class="share-diary-box">';
		html+='<ul>';
			html+='<li class="share_via_fb"><a href="javascript:fbShare(\''+"http://www.facebook.com/TestJtn/app_190322544333196"+'\', \''+"Journey to 9"+'\', \''+"My diary"+'\', \''+"http://www.appropolisinc.com/jtn/assets/img/facebook_icon.png"+'\', 520, 350)" title="Facebook"><i class="fb-icon"></i>Facebook</a></li>';
			html+='<li class="share_via_twitter"><a id="btn-twitter" href="https://twitter.com/intent/tweet?hashtags=Journeyto9&original_referer=http%3A%2F%2Flocalhost%2Fjtn%2F&text=Journey%20to%209&tw_p=tweetbutton&url=https%3A%2F%2Fwww.facebook.com%2FTestJtn%2Fapp_190322544333196" title="Twitter"><i class="twit-icon"></i>Twitter</a></li>';
			html+='<li><a id="btn-share-email" title="Email"><i class="email-icon"></i>Email</a></li>';
			html+='<li>&nbsp;</li>';
			html+='</ul>';
		html+='</div>';
		$(".wrapper-share-diary").html(html);
		ownerID = $.cookie('session_code');
		get_points(ownerID);
		get_available_points(ownerID);
		$(".share_via_fb").click(function(){
			get_earn_points('1');
			setTimeout("update_sharepoints(ownerID,'1')", 1000);
			setTimeout("update_sharepoints(ownerID,'2')", 1000);
		});
		$(".share_via_twitter").click(function(){
			get_earn_points('2');
			setTimeout("update_sharepoints(ownerID,'1')", 1000);
			setTimeout("update_sharepoints(ownerID,'2')", 1000);
		});
		html="";
		
		html+='<div class="share-email-box">';
		html+='Share your journey thru email.<br /><small><i>Type e-mail separated by comma. ("e.g. you@domain.com,")</i></small>';
		html+='<input type="text" class="span3" name="email-add" id="email-add" placeholder="Type e-mail here." />';
		html+='<input type="submit" class="btn share-via-email" value="Share" />';
		html+='</div>';		
		$(".wrapper-share-email").html(html);
		$('#email-add').multipleInput();
		$(".share-via-email").click(function(){
			share_via_email();
		});
		$(".wrapper-share-diary").dialog({
			minHeight: 140,
			modal: true,
			autoOpen: false,
			show: {
				effect: "explode",
					duration: 300
				},
				hide: {
				effect: "explode",
					duration: 300
				},
			draggable: false
		});
		$(".wrapper-share-email").dialog({
			minHeight: 140,
			modal: true,
			autoOpen: false,
			show: {
				effect: "explode",
					duration: 300
				},
				hide: {
				effect: "explode",
					duration: 300
				},		
				buttons: {
					//"Yes": function() {
	
					//},
					//"No": function() {
					//	$(this).dialog("close");
					//}
				},
			draggable: false
		});		
		$(".wrapper-share-diary").dialog("open");
		setTimeout("bind_share_btn()",500);
	});	
});
(function( $ ){
	 
    $.fn.multipleInput = function() {

         return this.each(function() {

              // create html elements

              // list of email addresses as unordered list
              $list = $('<ul />');

              // input
              var $input = $('<input type="text" />').keyup(function(event) {

                   if(event.which == 32 || event.which == 188) {
                        // key press is space or comma
                        var val = $(this).val().slice(0, -1); // remove space/comma from value
                        
                        // append to list of emails with remove button
                        $list.append($('<li class="multipleInput-email img-rounded" id="'+ val +'"><span>' + val + '</span></li>')
                             .append($('<a href="#" class="multipleInput-close" title="Remove" />')
                                  .click(function(e) {
                                       $(this).parent().remove();
                                       e.preventDefault();
                                       var email_add = new Array();
                                    	$('.multipleInput-email span').each(function() {
                                    		email_add.push($(this).html());
                                    		$("#strShareEmail").val(email_add);
                                    	});
                                  })
                             )
                        );
                        $(this).attr('placeholder', '');
                        // empty input
                        $(this).val('');
                        var email_add = new Array();
                        $('.multipleInput-email span').each(function() {
                        	email_add.push($(this).html());
                        	$("#strShareEmail").val(email_add);
                        });
                   }
              });
              var $container = $('<div class="multipleInput-container" />').click(function() {
                   $input.focus();
              });
              $container.append($list).append($input).insertAfter($(this));

              // add onsubmit handler to parent form to copy emails into original input as csv before submitting
              var $orig = $(this);
              $(this).closest('input').submit(function(e) {

                   var emails = new Array();
                   $('.multipleInput-email span').each(function() {
                        emails.push($(this).html());
                   });
                   emails.push($input.val());

                   $orig.val(emails.join());
                  $("#strShareEmail").val(emails);
                   
              });

              return $(this).hide();

         });

    };
})( jQuery );
function validateEmail(field) {
    var regex=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
    return (regex.test(field)) ? true : false;
}
function validateMultiEmails(strEmail) {
    if (strEmail != '') {
        var result = strEmail.split(',');
        for (var i = 0; i < result.length; i++) {
            if (result[i] != '') {
                if (!validateEmail(result[i])) {
                    alert(result[i] +" is not valid!");
                    return false;
                }
            }
        }
    }
    return true;
}
function share_via_email(){
	//var strName_sender = $("#strShareEmail").val();
	var strEmail = $("#strShareEmail").val();
	if(validateMultiEmails(strEmail)==true){
		send_share_email();
		ownerID = $.cookie('session_code');
		get_points(ownerID);
		get_available_points(ownerID);
		get_earn_points('3');
	}
}
function send_share_email(){
	owner = $.cookie('owner');
	ownerID = $.cookie('session_code');
	var strEmail = $("#strShareEmail").val();
	xfunc = "module/send_share_email";
	data_sent = {
			'strName':owner,
			'strEmail':strEmail
	};
	$.ajax({
		type: "POST", // request type POST
		url: base_url+xfunc, // post to PHP file
		data: data_sent, // request send to PHP file
		dataType:'json',
		success: function(result){
			$(".share-email-box").html("You shared successfully your journey.");
			setTimeout("update_sharepoints(ownerID,'1')", 1000);
			setTimeout("update_sharepoints(ownerID,'2')", 1000);
		}
	});
}
function get_earn_points(viaPoints){
	xfunc = "module/get_earn_points";
	data_sent = {
			'intID':viaPoints
	};
	$.ajax({
		type: "POST",
		url: base_url+xfunc,
		data: data_sent,
		dataType: 'json',
		success: function(result){
			$("#intEarnPoints").val(result.intEarn);
		}
	});
}
function get_available_points(intID){
	xfunc = "module/get_available_points";
	data_sent = {
			'intID':intID
	};
	$.ajax({
		type: "POST",
		url: base_url+xfunc,
		data: data_sent,
		dataType: 'json',
		success: function(result){
			$("#intAvailablePoints").val(result.intPoints);
		}
	});
	
}
function get_points(intID){
	xfunc = "module/get_points_via_share";
	data_sent = {
			'intID':intID
	};
	$.ajax({
		type: "POST",
		url: base_url+xfunc,
		data: data_sent,
		dataType: 'json',
		success: function(result){
			$("#intGetPoints").val(result.intPoints);
		}
	});
	
}
function update_available_points(intID,intPointsID){
	var intEarnPoints = $("#intEarnPoints").val();
	var intAvailablePoints = $("#intAvailablePoints").val();
	var newPoints = intAvailablePoints*1+intEarnPoints*1;
	xfunc = "module/update_available_points";
	data_sent = {
			'intID':intID,
			'intPoints':newPoints,
			'intPointsID':intPointsID,
	};
	$.ajax({
		type: "POST",
		url: base_url+xfunc,
		data: data_sent,
		dataType: 'json',
		success: function(result){
			$("#intAvailablePoints").val('');
		}
	});
}
function update_sharepoints(intID,intPointsID){
	var intGetPoints = $("#intGetPoints").val();
	var intEarnPoints = $("#intEarnPoints").val();
	var intAvailablePoints = $("#intAvailablePoints").val();
	if(intPointsID==1){
		var newPoints = intGetPoints*1+intEarnPoints*1;
	} 
	if(intPointsID==2){
		var newPoints = intAvailablePoints*1+intEarnPoints*1;
	}
	xfunc = "module/update_points_via_share";
	data_sent = {
			'intID':intID,
			'intPoints':newPoints,
			'intPointsID':intPointsID,
	};
	$.ajax({
		type: "POST",
		url: base_url+xfunc,
		data: data_sent,
		dataType: 'json',
		success: function(result){
			$("#intGetPoints").val('');
			$("#intEarnPoints").val('');
		}
	});
}
function bind_share_btn(){
	$('#btn-share-email').click(function(){
		$('.wrapper-share-diary').dialog('close');
		$(".wrapper-share-email").dialog("open");
	});
	$('#btn-twitter').click(function(){
		$('.wrapper-share-diary').dialog('close');
	});
}
function list_module(){
	var ksort = 0;
	var asort = 0;
	login_icons = {};
	panel_icons = {};
	xfunc = "module/get_list_module";
	
	data_sent = {};
		
		$.ajax({ 
			type: "POST", // request type POST
			url: base_url+xfunc, // post to PHP file
			data: data_sent, // request send to PHP file
			dataType:'json',
			success: function(result){ // result = return from php request
				$(result.strName).each(function(k,v){	
					if(result.intShowPanel[k]==1){
						if(result.intShowLogin[k]==1){
							if(ksort<result.intOrderLogin[k]){
								ksort = result.intOrderLogin[k];
							}
							html_icons_login = '';
							html_icons_login +='<li>';
								html_icons_login +='<a href="'+result.strLinkLogin[k]+'">';
									html_icons_login +='<span><img src="'+base_url+'assets/img/'+result.strImgLink[k]+'"></span>';
									html_icons_login +='<span>'+result.strName[k]+'</span>';
								html_icons_login +='</a>';
							html_icons_login +='</li>';
							login_icons[result.intOrderLogin[k]]=html_icons_login;
							
						}
						if(asort<result.intOrderPanel[k]){
							asort = result.intOrderPanel[k];
						}
						html_icons_panel = '';
						html_icons_panel +='<li>';
							html_icons_panel +='<div class="icons-shadow img-rounded">';
								html_icons_panel +='<div class="icons-border img-rounded">';
									html_icons_panel +='<a class="box-bg img-rounded" href="'+result.strLink[k]+'">';
										if($.trim(result.strAltImgLink[k])==""){
											html_icons_panel +='<span><img src="'+base_url+'assets/img/'+result.strImgLink[k]+'"></span>';
										} else {
											html_icons_panel +='<span><img src="'+base_url+'assets/img/'+result.strAltImgLink[k]+'"></span>';
										}
										html_icons_panel +='<span>'+result.strName[k]+'</span>';
									html_icons_panel +='</a>';
								html_icons_panel +='</div>';
							html_icons_panel +='</div>';
						html_icons_panel +='</li>';
						panel_icons[result.intOrderPanel[k]]=html_icons_panel;		
					}
				});
				
				html_login = '<ul>';
				for(x=0;x<=ksort;x++){
					if($.trim(login_icons[x])!=""){
						html_login +=login_icons[x];
					}
								
				}
				html_login+='</ul>';
				
				html_panel = '<ul>';
				for(x=0;x<=asort;x++){
					if($.trim(panel_icons[x])!=""){
						html_panel +=panel_icons[x];
					}
								
				}				
				html_panel += '</ul>';
				
				$('#icons-login').html(html_login);
				$('#icons-panel').html(html_panel);
			}
		});	
}
